<?php
namespace app\admin\controller;
use app\admin\controller\Base;
class Area extends Base{
    private $obj;
    
    public function _initialize() {
       $this->obj=model("Area");
    }
    //area/index
    public function index(){
        $parentId=input("get.parent_id",0,"intval");
        $areas=$this->obj->getFirstAreas($parentId);
        
        return  $this->fetch("",[
            "areas"=>$areas,
        ]);
        
    }
    //area/add
    public function add(){
     $areas=$this->obj->getNormalFirstArea();
     $citys=model("City")->getNormalFirstCitys();
     return $this->fetch("",[
      "areas"=>$areas,
      "citys"=>$citys,
     ]);
        
    }
    //area/save
    public function save(){
       if(!request()->isPost()){
           $this->error("非法请求");
       } 
      $data=input("post.");
      
      $validate=validate("area");   
      if(!$validate->scene("add")->check($data)){
          $this->error($validate->getError());
      } 
      //修改
      if(!empty($data["id"])){
          $this->update($data);
      }
      
      
     //交给model层处理
      $res=$this->obj->add($data);
      if($res){
          $this->success("添加成功");
      }else{
          $this->error("添加失败");
      }
    }
    
    //状态和删除
    
    public function status(){
        if(!request()->isGet()){
            $this->error("非法请求");
        }
        //数据
        $data=input("get.");
        $validate=validate("Area");
        if(!$validate->scene("status")->check($data)){
            $this->error($validate->getError());
        }
        
        $res=$this->obj->save(["status"=>$data['status']],["id"=>$data['id']]);
        if($res){
            $this->success("修改成功");
        }else{
            $this->error("修改失败");
        }
        
        
    }
    //修改
    public function edit($id=0){
        if(intval($id)<0){
            $this->error("参数不准确");
        }
        $area=$this->obj->get($id);
        $areas=$this->obj->getNormalFirstArea();
        $citys=model("City")->getNormalFirstCitys();
        return $this->fetch("",[
            "area"=>$area,
            "areas"=>$areas,
            "citys"=>$citys,
        ]);
        
    }
    
    public function update($data){
        //tp5中save特性来
        $res=$this->obj->save($data,["id"=>intval($data['id'])]);
        if($res){
            $this->success("修改成功");
        }else{
            $this->error("修改失败");
        }
    }
    //排序
    public function listorder($id,$listorder){
      $res=$this->obj->save(["listorder"=>$listorder],["id"=>$id]);  
      if($res){
          return $this->result($_SERVER['HTTP_REFERER'],1,'success');
      }else{
          return $this->result($_SERVER['HTTP_REFERER'],0,'error');
      }  
        
    }
    
}
